<template>
<div class="compHeader">
  <div class="main">
     <div class="header_l">
        <a href="index.html">
           <img src="@/assets/images/logo_1.png" />
           <img src="@/assets/images/logo_2.png" />
        </a>
        <span>www.xxx.com</span>
     </div>
     <div class="header_c">
        <input name="" type="text" placeholder="请输入关键字..." class="keyword"/>
        <input name="" type="button" class="btnsearch"/>
     </div>
     <div class="header_r">
        <a href="login.html">个人登录</a>
        <a href="register.html">注册</a>
     </div>
  </div>
</div>
<div class="compMain">
  <div class="main">
     <div class="CpLogo">
        <img src="@/assets/images/company.gif" />
     </div>
     <div class="CpDetail">
        <div class="CompanyName">
           <span class="title">{{enterpriseInfo.enterpriseName}}</span>
           <img src="@/assets/images/16.png" />
           <span  v-if="!isInterested(enterpriseId)" @click="interestNow(enterpriseId)" class="guanzhu">+ 关注</span>
           <span v-else href="javascript:void(0);" class="guanzhu">已关注</span>

        </div>
        <p>{{getNatureDescription(enterpriseInfo.nature)}} | {{getSizeDescription(enterpriseInfo.size)}} | {{enterpriseInfo.industryName}}</p>
        <p><a href="">http://www.xxxxxx.com</a></p>
        <p>{{enterpriseInfo.address}}</p>
     </div>
  </div>
</div>
<!-- 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -->
<div class="compcontent">
   <div class="comcontentL">
     <ul id="tabcompany">
        <li :class="{ Active: currentTab === 'company' }" @click="currentTab = 'company'">公司介绍</li>
        <li :class="{ Active: currentTab === 'jobs' }" @click="currentTab = 'jobs'">招聘职位</li>
       <div class="clear"></div>
    </ul>
    <div class="clear"></div>
    <div id="contentcompany">
       <ul v-if="currentTab === 'company'" style="display:block">
          <div class="conts">
            {{ enterpriseInfo.introduce }}
          </div>
       </ul>
       <!-- -------------------------------- -->
       <div v-if="currentTab === 'jobs'">
        <div class="zhiwei" v-for="job in searchResults" :key="job.id" >
            <div class="zhiweiL" >
              <div class="zw1">
                <a href="job_info.html">{{ job.jobName }}</a>
                <span>[{{ job.workSpace }}]</span>
              </div>
              <div class="zw2">
                <span class="red">{{ job.minSalary }}K-{{ job.maxSalary }}K</span> | 招聘{{ job.needNumber }}人 | {{ job.jobNature }} | 年龄{{ job.limitAge }} | 经验：{{ job.experience }} | {{ formatRelativeTime(job.updateTime) }}刷新
              </div>
              <div class="zw3">岗位职责：{{ job.jobDetails }}</div>
              
            </div>
            <div class="zhiweiR">
              <a v-if="!isApplied(job.id)" @click="applyNow(job.id)" class="ljsqbtn">立即申请</a>
              <a v-else href="javascript:void(0);" class="ysqbtn">已申请</a>
            </div>
          </div>
       </div>
    </div>
   </div>
</div>

<div class="clear"></div>
<div class="footer">
</div>
  </template>
  
  <script setup>
import { ref, onMounted } from "vue";

import router from "@/router"; // 确保引入了路由配置
import storageUtils from '@/util';
import {getApplyJobs,postApplyJob,getInterestedEnterprises,interestEnterprise,getJobsByEnterpriseId2,getEnterpriseInfo2} from '@/api/jobApplyInterest'

// 使用 ref 来存储 enterpriseId 和 enterpriseInfo
const enterpriseId = ref(router.currentRoute.value.params.enterpriseId);
//console.log("333"+enterpriseId.value);
const enterpriseInfo = ref({});
const currentTab = ref('jobs'); // 默认显示公司介绍
const searchResults = ref([]); // 搜索结果

// 从 sessionStorage 获取当前登录用户的 userId
const userId = storageUtils.getSessionObject('loginUser').userId;

// 页面加载时调用
onMounted(() => {
  getEnterpriseInfo();
});

const getEnterpriseInfo =  async () => {
  try {
    // 发送请求到后端获取企业信息
    const response = await getEnterpriseInfo2(enterpriseId.value);
    // const response = await axios.get(`/enterprise/getEnterpriseInfo`, {
    //   params: { id: enterpriseId.value },
    // });
    // 将获取到的企业信息存储在 enterpriseInfo 中
    enterpriseInfo.value = response.data.data; // 确保这里正确处理了返回的数据结构
    //console.log("企业信息加载完成：", enterpriseInfo.value); // 确保在数据加载完成后打印
  } catch (error) {
    console.error("获取企业信息失败:", error);
  }
};
//-------------------------------------------------888888888888888888888888888888888基本信息显示已完成，接下来做关注。
// 用来放关注过的企业的 id 的数组，在页面加载的时候判断该显示关注还是已关注
const interestedEnterpriseIds = ref(new Set());

// 发请求去获取已关注的企业
const fetchInterestedEnterprises = async () => {
  try {
    const response = await getInterestedEnterprises(userId);
    // const response = await axios.get("/interest/getInterestedEnterprises", {
    //   params: { userId }
    // });

    if (response.data && response.data.code === 0) {
      const interestedEnterprises = response.data.data || [];
      // 将所有 enterpriseId 转换为字符串
      interestedEnterpriseIds.value = new Set(interestedEnterprises.map(item => String(item.enterpriseId)));

    } else {
      console.error('获取关注记录失败：', response.data.message);
    }
  } catch (error) {
    console.error('请求失败：', error);
  }
};

// 页面加载时调用 fetchInterestedEnterprises 方法
onMounted(() => {
  fetchInterestedEnterprises();
});

const isInterested = (enterpriseId) => {
  //console.log("enterpriseId 的类型：", typeof enterpriseId); // string
  //console.log("interestedEnterpriseIds 中的值：", Array.from(interestedEnterpriseIds.value)); // [1]
  //console.log("interestedEnterpriseIds 中的值类型：", Array.from(interestedEnterpriseIds.value).map(id => typeof id)); // ['number']

  const result = interestedEnterpriseIds.value.has(enterpriseId);
  //console.log("检查结果：", result); // 应该是 true
  return result;
};//老子检查了三个小时，就因为enterpriseId是string，数组里是int，全转成字符串。

// 点击关注，插入 interest 表
const interestNow = async (enterpriseId) => {
  const nowtime = new Date().toISOString();
  try {
    const response = await interestEnterprise(userId, enterpriseId,nowtime);
    // const response = await axios.post("/interest/addInterest", {
    //   userId: userId,
    //   enterpriseId: enterpriseId,
    //   updateTime: new Date().toISOString()
    // });

    if (response.data && response.data.code === 0) {
      interestedEnterpriseIds.value.add(enterpriseId); // 添加到已关注列表
    } else {
      alert("关注失败：" + response.data.message);
    }
  } catch (error) {
    console.error("关注请求失败：", error);
    alert("请求失败，请稍后重试！");
  }
};
//-------------------------------------------------999999999999999999999999999999999招聘职位。
// 获取 招聘职位
const isLoading = ref(false);

const getJobsByEnterpriseId = async () => {
  isLoading.value = true; // 开始加载
  try {
    const response = await getJobsByEnterpriseId2(enterpriseId.value);
    // const response = await axios.get("/job/getJobsByEnterpriseId", {
    //   params: {
    //     enterpriseId: enterpriseId.value,
    //   },
    // });

    if (response.data && response.data.code === 0) {
      const items = response.data.data || []; // 确保即使没有数据，也是一个空数组
      items.forEach(transformJobData); // 转换数据
      searchResults.value = items; // 更新数据
    } else {
      console.error("获取职位信息失败：", response.data.message);
    }
  } catch (error) {
    console.error("获取职位信息请求失败：", error);
  } finally {
    isLoading.value = false; // 加载完成
  }
};

// 页面加载时调用 getJobsByEnterpriseId 方法
onMounted(() => {
  getJobsByEnterpriseId(); // 调用获取职位信息的方法
});
//----------------------------------**************************************立即申请
// 用来放申请过的职位的 id 的数组
const appliedJobIds = ref([]);

// 发请求去申请表
const fetchAppliedJobs = async () => {
  try {
    const response = await getApplyJobs(userId);
    // const response = await axios.get(`/apply/getAppliedJobs`, {
    //   params: { userId }
    // });

    // 检查后端返回的 code 是否为 0（成功）
    if (response.data && response.data.code === 0) {
      // 提取后端返回的职位数据
      const appliedJobs = response.data.data || [];
      appliedJobIds.value = appliedJobs.map(item => item.jobId); // 假设后端返回的字段是 jobId
      console.log(appliedJobs);
    } else {
      // 如果返回失败，打印错误信息
      console.error('获取申请记录失败：', response.data.message);
    }
  } catch (error) {
    // 网络请求失败或其他错误
    console.error('请求失败：', error);
  }
};

// 页面加载时调用 fetchAppliedJobs 方法
onMounted(() => {
  fetchAppliedJobs();
});

// 检查是否已申请
const isApplied = (jobId) => {
  return appliedJobIds.value.includes(jobId);
};

//点击立即申请，插入apply表
// 发送申请请求
const applyNow = async (jobId) => {
  const nowtime = new Date().toISOString();
  try {
    const response = await postApplyJob(userId, jobId,nowtime);
    // const response = await axios.post("/apply/applyJob", {
    //   userId: userId,
    //   jobId: jobId,
    //   updateTime: new Date().toISOString() // 发送当前时间
    // });

    if (response.data && response.data.code === 0) {
      appliedJobIds.value.push(jobId); // 添加到已申请列表
    } else {
      alert("申请失败：" + response.data.message);
    }
  } catch (error) {
    console.error("申请请求失败：", error);
    alert("请求失败，请稍后重试！");
  }
};








//***********************************************************************下面是一些无关紧要的辅助函数 */
const natureMap = ref({
  0: "非国企",
  1: "国企",
});

const sizeMap = ref({
  1: "少于50人",
  2: "50-200人",
  3: "200人以上",
});

// 转换企业性质
const getNatureDescription = (nature) => {
  return natureMap.value[nature] || "未知";
};

// 转换企业规模
const getSizeDescription = (size) => {
  return sizeMap.value[size] || "未知";
};
const transformJobData = (job) => {
    console.log("转换前的职位数据：", job);
  // 转换学历要求
  const degreeMap = ["大专", "本科", "硕士", "博士"];
  job.minDegree = degreeMap[job.minDegree] || "未知";

  // 转换工作经验
  const experienceMap = ["有经验", "不限"];
  job.experience = experienceMap[job.experience] || "未知";

  // 转换工作地点
  const workSpaceMap = ["北京", "上海", "广州","深圳"];
  job.workSpace = workSpaceMap[job.workSpace] || "未知";

  // 转换招聘方式
  const natureMap = ["全职", "兼职", "实习"];
  job.jobNature = natureMap[job.jobNature] || "未知";

  console.log("转换后的职位数据：", job);

};

// 定义相对时间格式化函数
const formatRelativeTime = (timestamp) => {
  //将1742177124000时间转换成 2017-12-05的格式
   // 创建一个 Date 对象
   const date = new Date(timestamp);

// 获取年、月、日
const year = date.getFullYear(); // 获取年份
const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份，+1 是因为 getMonth() 返回的是从 0 开始的索引
const day = String(date.getDate()).padStart(2, '0'); // 获取日期

// 返回格式化的日期字符串
return `${year}-${month}-${day}`;
};

</script>
  
  <style>
 
  </style>